package net.wanho.config;

import net.wanho.shiro.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2024-08-16 16:01
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 设置url过滤规则
        Map<String,String> map = new LinkedHashMap();
        map.put("/register.jsp", "anon");
        map.put("/login.jsp", "anon");
        map.put("/user/login", "anon");
        map.put("/user/register", "anon");

        map.put("/**", "authc");

        // 设置未登录时默认跳转页面
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置自定义的realm
        securityManager.setRealm(shiroRealm);

        return securityManager;
    }

    @Bean
    public ShiroRealm shiroRealm(){
        ShiroRealm realm = new ShiroRealm();
        realm.setName("myRealm");

        // 创建密码匹配器，支持散列算法（默认使用的是SimpleCredentialsMatcher）
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        // 设置凭证匹配器
        realm.setCredentialsMatcher(credentialsMatcher);

        return realm;
    }

}
